package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Commodity;
import cn.wolfcode.trip.base.domain.TransactionRecord;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.query.TransactionRecordQuery;
import cn.wolfcode.trip.base.service.ICommodityService;
import cn.wolfcode.trip.base.service.ITransactionRecordService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 交易记录控制器
 */
@RestController
@RequestMapping("transactionRecords")
public class TransactionRecordController {

    @Autowired
    private ITransactionRecordService transactionRecordService;
    @Autowired
    private ICommodityService commodityService;

    @GetMapping
    public PageInfo list(@ModelAttribute("qo")QueryObject qo, Model model){
        return transactionRecordService.query(qo);
    }

    /**
     * 保存交易记录
     * @param transactionRecord
     * @return
     */
    @PostMapping
    public JSONResult save(TransactionRecord transactionRecord){
        //获取商品的id
        Long id = transactionRecord.getCommodity().getId();
        //根据id查询商品的价格
        Commodity commodity = commodityService.getById(id);
        transactionRecord.setDealPrice(commodity.getPrice());
        transactionRecord.setDealTime(new Date());
        transactionRecordService.save(transactionRecord);
        return new JSONResult();
    }

    /**
     * 前台查询交易记录
     * @return
     */
    @GetMapping("/records")
    public PageInfo listForApp(TransactionRecordQuery qo){
        qo.setOrderBy("tr.deal_time desc");
        PageInfo records= transactionRecordService.queryForApp(qo);
        return records;

    }

    /**
     * 删除记录的操作
     */
    @DeleteMapping
    public JSONResult deleteRecord(Long id){
        transactionRecordService.delete(id);
        return new JSONResult();  //象征性返回成功
    }


}
